from django.shortcuts import render, HttpResponse

# Create your views here.
from luffyapi.utils.response import APIResponse
from rest_framework.decorators import action

from django.core.cache import cache
from django.conf import settings

from .throttlings import SMSThrottle
#
# def index(request):
#     print(request.method)
#     return HttpResponse('你看到我饿了')


## 登录接口
# 自动生成路由，post请求，跟数据有关系
from rest_framework.viewsets import ViewSetMixin, ViewSet
from rest_framework.views import APIView
from rest_framework.decorators import action
from .serializer import UserModelSerializer, UserPhoneModelSerializer, UserRegisterModelSerializer
from . import models
import re
from luffyapi.libs.tx_sms import send, get_code


# class LoginView(ViewSetMixin,APIView):
class UserView(ViewSet):
    # throttle_classes = []

    @action(methods=['POST'], detail=False)
    def login(self, request, *args, **kwargs):

        # 序列化类
        ser = UserModelSerializer(data=request.data)
        if ser.is_valid():
            # 登录成功
            token = ser.context['token']
            user = ser.context['user']
            # ser2=UserModelSerializer(instance=user)
            return APIResponse(token=token, username=user.username, id=user.id)
        else:
            # 登录失败
            return APIResponse(code=101, msg='用户名或密码错误')

    @action(methods=['POST'], detail=False)
    def login_phone(self, request, *args, **kwargs):

        # 序列化类
        ser = UserPhoneModelSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context['token']
        user = ser.context['user']
        return APIResponse(token=token, username=user.username, id=user.id)

    @action(methods=['POST'], detail=False)
    def register(self, request, *args, **kwargs):
        # 序列化类
        ser = UserRegisterModelSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()  # 新增会触发，serializer的create方法,重写create方法
        return APIResponse(code=100, msg='注册成功')

    ##手机号是否存在接口：get :user/check_phone?phone=1333333
    ## 自动生成路由,把它直接写到原来写login的视图类中
    @action(methods=['GET'], detail=False)
    def check_phone(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        if re.match('^1[3-9][0-9]{9}$', phone):
            user = models.User.objects.filter(mobile=phone).first()
            if user:
                return APIResponse(msg='手机号存在')
            else:
                return APIResponse(code=101, msg='手机号不存在')

        else:
            return APIResponse(code=102, msg='手机号不合法')


class SmsView(ViewSet):
    throttle_classes = [SMSThrottle]

    # 发送短信接口，写在这里面
    # 限制同一个手机号短信一分钟，只能发送一次
    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        if phone:
            if re.match('^1[3-9][0-9]{9}$', phone):
                code = get_code()
                res = send(phone, code)
                # 短信验证码要，存在哪？django缓存中（默认在内存中，redis）
                cache.set(settings.SMS_PHONE_CACHE % phone, code, 60)
                if res:
                    return APIResponse(msg='短信发送成功')
                else:
                    return APIResponse(code=101, msg='短信发送失败')

            else:
                return APIResponse(code=102, msg='手机号不合法')
        else:
            return APIResponse(code=103, msg='没有携带手机号')

from django_redis import get_redis_connection

# def test(request):
#     from luffyapi.libs.redis_pool import POOL
#     from redis import Redis
#     conn = Redis(connection_pool=POOL)
#     name = conn.get('name')
#     return HttpResponse('name是：%s' % name)

# def test(request):
#     conn=get_redis_connection()  # 从连接池中取一个连接
#     name = conn.get('name')
#     return HttpResponse('name颠覆三观待分割是：%s' % name)


def test(request):
    # 提交一个计算 90+80的任务
    from celery_task.home_task import add

    res=add.delay(90,80)
    return HttpResponse('任务已经提,任务id为：%s'%str(res))


def get_result_test(request):
    from celery.result import AsyncResult
    from celery_task import app
    id=request.GET.get('id')

    a = AsyncResult(id=id, app=app)
    if a.successful():
        result = a.get()
        print(result)
    elif a.failed():
        print('任务失败')
    elif a.status == 'PENDING':
        print('任务等待中被执行')
    elif a.status == 'RETRY':
        print('任务异常后正在重试')
    elif a.status == 'STARTED':
        print('任务已经开始被执行')

    return HttpResponse('任务执行的结果是%s'%result)